package com.example.grpc;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 演示应用程序，用于启动服务器并运行客户端测试。
 */
public class DemoApp {
    public static void main(String[] args) {
        System.out.println("=== Java gRPC Demo ===");

        // 在单独的线程中启动服务器
        ExecutorService serverExecutor = Executors.newSingleThreadExecutor();
        serverExecutor.submit(() -> {
            try {
                GreeterServer.main(new String[]{});
            } catch (Exception e) {
                System.err.println("Server error: " + e.getMessage());
            }
        });

        // 给服务器启动时间
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        // 运行客户端测试
        try {
            GreeterClient client = new GreeterClient("localhost", 50051);

            System.out.println("\n--- Testing with 'World' ---");
            client.greet("World");

            System.out.println("\n--- Testing with 'gRPC' ---");
            client.greet("gRPC");

            System.out.println("\n--- Testing with 'Java' ---");
            client.greet("Java");

            client.shutdown();

        } catch (Exception e) {
            System.err.println("Client error: " + e.getMessage());
        }

        // 关闭服务器
        try {
            System.out.println("\nShutting down server...");
            serverExecutor.shutdownNow();
            serverExecutor.awaitTermination(5, TimeUnit.SECONDS);
            System.out.println("Demo completed successfully!");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("Shutdown interrupted");
        }
    }
}